package com.hoshiibuy.sys.permission.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiibuy.common.exception.CommonError;
import com.hoshiibuy.common.exception.ServiceException;
import com.hoshiibuy.common.rpc.Response;
import com.hoshiibuy.sys.permission.dao.SysOrganizationMapper;
import com.hoshiibuy.sys.permission.dao.SysPermissionesMapper;
import com.hoshiibuy.sys.permission.dao.SysPlatformMapper;
import com.hoshiibuy.sys.permission.entity.SysOrganization;
import com.hoshiibuy.sys.permission.entity.SysPlatform;
import com.hoshiibuy.sys.permission.entity.param.RObject;
import com.hoshiibuy.sys.permission.feign.IdGeneratorRemote;
import com.hoshiibuy.sys.permission.feign.Neo4jRemote;
import com.hoshiibuy.sys.permission.service.ISysOrganizationService;

/**
 * <p>
 * 系统组织 服务实现类
 * </p>
 *
 * @author Mr.Wu
 * @since 2019-04-18
 */
@Service
public class SysOrganizationServiceImpl extends ServiceImpl<SysOrganizationMapper, SysOrganization>
		implements ISysOrganizationService {

	@Autowired
	private Neo4jRemote neo4jRemote;

	@Autowired
	private IdGeneratorRemote idGeneratorRemote;

	@Autowired
	private SysPermissionesMapper sysPermissionesMapper;

	@Autowired
	private SysOrganizationMapper sysOrganizationMapper;

	@Autowired
	private SysPlatformMapper sysPlatformMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response addDept(SysOrganization param) {
		// 获取全局id
		String id = idGeneratorRemote.getId();
		if (StringUtils.isBlank(id)) {
			throw new ServiceException(CommonError.error("id服务失败"));
		}
		// 调用内置工具产生ID
		param.setId(Long.valueOf(id));
		param.setCreatedtime(LocalDateTime.now());
		sysOrganizationMapper.insert(param);
		Response result = null;
		if (param.getPid() != null) {
			// 插入上级部门节点

			// 搜索上级部门名称
			SysOrganization parentDept = sysOrganizationMapper.selectById(param.getPid());
			if (parentDept == null) {
				throw new ServiceException(CommonError.error("搜索上级平台失败"));
			}
			// 插入neo4j节点
			RObject neo4jParam = new RObject();
			// 部门所属上级部门名称
			neo4jParam.setLabel(parentDept.getName());
			neo4jParam.setUuid(id);
			neo4jParam.addProperty("uuid", id);
			neo4jParam.addProperty("name", param.getName());
			result = neo4jRemote.addRole(neo4jParam);

		} else if (param.getPlatformid() != null) {
			// 插入平台节点

			// 搜索上级平台名称
			SysPlatform platform = sysPlatformMapper.selectById(param.getPlatformid());
			if (platform == null) {
				throw new ServiceException(CommonError.error("搜索上级平台失败"));
			}
			// 插入neo4j节点
			RObject neo4jParam = new RObject();
			// 部门所属平台名称
			neo4jParam.setLabel(platform.getName());
			neo4jParam.setUuid(id);
			neo4jParam.addProperty("uuid", id);
			neo4jParam.addProperty("name", param.getName());
			result = neo4jRemote.addRole(neo4jParam);
		}
		if (result != null && !result.isSuccess()) {
			throw new ServiceException(CommonError.error("neo4j服务失败," + result.getMsg()));
		} else if (result == null) {
			throw new ServiceException(CommonError.error("neo4j服务失败"));
		}
		return Response.success("新增成功");
	}

	@Override
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response deleteDept(String id) {
		int count = sysOrganizationMapper.deleteById(id);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("删除失败"));
		} else {
			return Response.success("删除成功");
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
	public Response<SysOrganization> getDetail(String id) {
		// TODO Auto-generated method stub
		SysOrganization sysOrganization = sysOrganizationMapper.selectById(id);
		if (sysOrganization == null) {
			return Response.failed("数据不存在");
		} else {
			return Response.data(sysOrganization);
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5(Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	public Response<List<SysOrganization>> getList(Wrapper<SysOrganization> queryWrapper) {
		return Response.data(sysOrganizationMapper.selectList(queryWrapper));
	}

	@Override
	@CacheEvict(cacheNames = { "sysOrganization" }, allEntries = true)
	public Response updateDept(SysOrganization param) {
		// TODO Auto-generated method stub
		int count = sysOrganizationMapper.updateById(param);
		if (count <= 0) {
			throw new ServiceException(CommonError.error("修改失败"));
		} else {
			return Response.success("修改成功");
		}
	}

	@Override
	@Cacheable(cacheNames = "sysOrganization", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5('Page(current=' +#page.getCurrent() + ', size=' + #page.getSize() + '), Wrapper(SqlSelect=' +#queryWrapper.getSqlSelect() + ', SqlSegment=' +#queryWrapper.getSqlSegment() + ')')")
	public Response getPage(IPage<SysOrganization> page, Wrapper<SysOrganization> queryWrapper) {
		return Response.data(sysOrganizationMapper.selectPage(page, queryWrapper));
	}

}
